#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from datetime import datetime
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, BigInteger, String, Unicode, UnicodeText, DateTime
from controls.data_pool_mysql import engine

# 创建到数据库的连接,echo=True表示用logging输出调试结果
metadata = MetaData()
Session = sessionmaker()  # 创建了一个自定义了的 Session类
Session.configure(bind=engine)  # 将创建的数据库连接关联到这个session

"""user_third collection has
   userid:     用户id (int)
   type:       第三方登录类型 (str)
   userkey:    相关登录系统唯一标识 (str)
   ctime:      注册时间(datetime)
"""

USER_THIRD_WX_UNION, = ['weixin', ]

class UserThirdItem(object):  # 创建一个映射类

    def to_dict(self):
        res = {}
        res['userid'] = self.userid
        res['type'] = self.type
        res['userkey'] = self.userkey
        res['ctime'] = self.ctime.strftime("%Y-%m-%d %H:%M:%S")\
            if self.ctime else ""
        return res

    def __repr__(self):
        return "%d" % (self.userid)


user_third_table = Table(
    'user_third', metadata,
    Column('id', Integer, primary_key=True),
    Column('userid', Integer, index=True, nullable=False),
    Column('type', Unicode(16), nullable=True),
    Column('userkey', Unicode(191), index=True, nullable=False),
    Column('ctime', DateTime, default=datetime.now, nullable=False),
)

mapper(UserThirdItem, user_third_table)  # 把表映射到类


def create_user_third_table_if_not_exist():
    metadata.create_all(engine)  # 在数据库中生成表
    # mapper( UserBaseItem, user_base_table ) #把表映射到类


def add_user_third_item(p_item):
    item = UserThirdItem()
    item.userid = p_item['userid']
    item.type = p_item['type']
    item.userkey = p_item['userkey']
    try:
        session = Session()
        session.add(item)  # 往session中添加内容
        session.flush()  # 保存数据
        session.commit()  # 数据库事务的提交,sisson自动过期而不需要关闭
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()
        # session.remove()


def get_user_third_by_userid_and_type(p_userid, p_type):
    try:
        session = Session()
        item = session.query(UserThirdItem)\
            .filter_by(userid=p_userid, type=p_type).first()
        if not item:
            return None
        return item.to_dict()
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def get_user_third_by_type_and_userkey(p_type, p_userkey):
    try:
        session = Session()
        item = session.query(UserThirdItem)\
            .filter_by(userkey=p_userkey, type=p_type).first()
        if not item:
            return None
        return item.to_dict()
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


if __name__ == "__main__":
    create_user_third_table_if_not_exist()
    item1 = {
        'userid': 1234,
        'type': USER_THIRD_WX_UNION,
        'userkey': "opQe-w8CP0PercjnVEgiIFpIPhQU"
    }
    add_user_third_item(item1)
